{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch as tc\n",
    "from scipy.sparse.linalg import eigsh\n",
    "from BasicFun import eigs_AD"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "利用scipy中的本征值分解求解最大本征值与本征向量\n",
      "矩阵的最大本征值为：\n",
      "3.2150984\n",
      "矩阵的最大本征向量为：\n",
      "[ 0.27584127 -0.19868533  0.7532839   0.41773033  0.09765212  0.36464298]\n",
      "\n",
      "利用自动微分求解最大本征值与本征向量\n",
      "矩阵的最大本征值为：\n",
      "3.2150981426239014\n",
      "矩阵的最大本征向量为：\n",
      "[ 0.2758419  -0.19868495  0.7532835   0.41773018  0.09765261  0.36464378]\n"
     ]
    }
   ],
   "source": [
    "# 自动微分求解实对称矩阵的本征值与本征向量\n",
    "\n",
    "# 构建随机实对称矩阵\n",
    "dim = 6\n",
    "M = tc.randn(dim, dim)\n",
    "M = M + M.t()\n",
    "\n",
    "\n",
    "print('利用scipy中的本征值分解求解最大本征值与本征向量')\n",
    "lm0, v0 = eigsh(M.numpy(), k=1, which='LA')\n",
    "print('矩阵的最大本征值为：')\n",
    "print(lm0[0])\n",
    "print('矩阵的最大本征向量为：')\n",
    "print(v0.reshape(-1, ))\n",
    "\n",
    "print('\\n利用自动微分求解最大本征值与本征向量')\n",
    "lm1, v1 = eigs_AD(M)\n",
    "print('矩阵的最大本征值为：')\n",
    "print(lm1.item())\n",
    "print('矩阵的最大本征向量为：')\n",
    "print(v1.data.to('cpu').numpy().reshape(-1, ))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
